package m.jclecai.com.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.squareup.okhttp.Request;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.bean.VersionBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.service.DownloadService;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import rx.functions.Action1;

import static m.jclecai.com.utils.http.SystemUtils.getVersionName;


public class SettingActivity extends BaseActivity {
    int mDebugClickCount = 0;
    long mDebugLaskClickTime = 0;

    @BindView(R.id.rl_invite)
    public View mRlInvite;

    @Override
    public int getContentView() {
        return R.layout.activity_setting;
    }

    @Override
    public void initView() {
        leftOptionText("");
        setTitle("设置");
    }

    @Override
    protected void initData() {
        super.initData();
        //这里我们要做的一个逻辑就是显示或者隐藏邀请好友；
        UserBean userBean = PreferenceUtil.readUser(this);
       mRlInvite.setVisibility(View.VISIBLE);
       if (null!=userBean){
           String user_type = userBean.getUser_type();
           if (!TextUtils.isEmpty(user_type)){
               if("1".equals(userBean.getUser_type())){
                   //这里我们要显示具体
                   mRlInvite.setVisibility(View.VISIBLE);
               }
           }

       }

    }

    @OnClick({R.id.rl_push, R.id.rl_version, R.id.rl_suggest,
            R.id.rl_invite, R.id.rl_about, R.id.rl_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_push:
                //推送设置：
                break;
            case R.id.rl_version:
                //检查版本；
                checkVersion();
                break;
            case R.id.rl_suggest:
                startActivity(new Intent(this,ProductSuggestActivity.class));
                break;
            case R.id.rl_invite:
                //邀请别人
                checkLogin(new Callback() {
                    @Override
                    public void callbackSuccess() {
                        super.callbackSuccess();
                        startActivity(new Intent(SettingActivity.this,
                                InvitedFriendActivity.class));
                    }
                });
                break;
            case R.id.rl_about:
                //关于我们；
                startActivity(new Intent(this,AboutUSActivity.class));
                break;
            case R.id.rl_logout:
                //登出
                logout();
                break;
        }
    }

    /**
     * 请求服务器，来检查本地的版本和服务器是否一样；
     */
    private void checkVersion() {
        //1、获取本地版本信息；
        //2、请求服务器是否更新；
        //3、弹出对话框显示新版本特性；
        //4、启动Services;

        final String versionCode = getVersionCode();
        final String versionName = getVersionName();

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        final View view = View.inflate(this, R.layout.dialog_update_layout, null);
        builder.setView(view);

        DisPlay("检查版本中...");
        HttpManager.getAsyn(Constant_Url.GET_LATEST + "?version=" + versionName + "&type=android" + "&versionCode=" + versionCode+"&appstore="+ ChannelUtil.getChannel(), new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                //请检查网络；
                DisPlay("请检查网络...");
            }

            @Override
            public void onResponse(String response) {
                //判断返回结果：
                final VersionBean versionBean = FastOk.get(response, VersionBean.class);
                if (versionBean.getStatus().equals("1")) {

                    try{
                        //服务器返回的数据有问题
                        final AlertDialog alertDialog = builder.create();

                        RxPermissions rxPermissions = new RxPermissions(SettingActivity.this);
                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .subscribe(new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        if (aBoolean) {
                                            alertDialog.show();
                                        }else{
                                            DisPlay("获取权限失败！！！");
                                        }
                                    }
                                });


                        view.findViewById(R.id.tv_update).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //这里我们要做的一个操作就是升级；
                                Intent intent = new Intent(SettingActivity.this, DownloadService.class);

                                long apkSize = 0;

                                try {
                                    apkSize=Long.parseLong(versionBean.getApkSize());
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }

                                intent.putExtra(DownloadService.APK_SIZE,apkSize);

                                intent.putExtra(DownloadService.DOWNLOAD_URL,versionBean.getDownload());
                                startService(intent);
                                alertDialog.dismiss();
                            }
                        });
                        //这里表示需要更新；在这里写的话可以偷懒
                        view.findViewById(R.id.tv_no_update).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                alertDialog.dismiss();
                            }
                        });

                        String  content="版本:"+versionBean.getVersion()+"\n";

                        float v = Float.parseFloat(versionBean.getApkSize()) / 1024 / 1024;
                        //保留两位小数
                        content+="包大小:"+(float)(Math.round(v*100))/100+"m\n\n";


                        String[] split = versionBean.getContent().split(";");
                        content+="更新内容：\n";
                        for(int i=0;i<split.length;i++){
                            content+=split[i]+"。\n";
                        }
                        content+="升级的小伙伴,今天晚上更容易中大奖哦。";
                        ((TextView) view.findViewById(R.id.tv_content)).setText(content);

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    DisPlay("你已经是最新版了");
                }
            }
        });

    }

    /**
     * 这里我们获取版本号；
     * @return
     */
    private String getVersionCode() {

        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            int versionCode = packageInfo.versionCode;
            return versionCode+"";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }

    void logout() {
        showDialog();
        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }

        PreferenceUtil.clearUserInfo(SettingActivity.this);
        PreferenceUtil.writeBoolean(SettingActivity.this,PreferenceUtil.WEI_XIN_IS_BIND_PHONE_NUMBER,true);//这里微信登陆绑定了手机号码；
        PreferenceUtil.writeBoolean(SettingActivity.this,PreferenceUtil.IS_USER_NAME_EMPTY,false);//这里微信登陆绑定了手机号码；
        setResult(RESULT_OK);
        HttpManager.getAsyn(Constant_Url.LOGOUT, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                finish();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                finish();
            }
        });
    }

    @OnClick(R.id.flDebug)
    void debug() {
        long currentTime = System.currentTimeMillis();
        if (mDebugLaskClickTime == 0 || (currentTime - mDebugLaskClickTime) < 500) {
            if (++mDebugClickCount >= 10) {
                startActivity(new Intent(SettingActivity.this,DebugActivity.class));
                mDebugClickCount = 0;
            }
        } else {
            mDebugClickCount = 1;
        }
        mDebugLaskClickTime = currentTime;

        Log.d(TAG, "DebugClickCount:" + mDebugClickCount);
    }
}
